package com.csnj.core.Srvs.SysManager;

import com.csnj.common.biz.BaseBiz;
import com.csnj.core.constant.CoreConstants;
import com.csnj.core.dao.*;
import com.csnj.core.entity.SysMenu;
import com.csnj.core.entity.SysResourceAuthority;
import com.csnj.core.entity.SysRole;
import com.csnj.core.entity.SysRoleMember;
import com.csnj.core.entity.VO.AuthorityMenuTree;
import com.csnj.core.entity.VO.GroupUsers;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.logging.Logger;

/**
 * Created by xiabin on 2018/11/22.
 */
@Service
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class SysRoleSrvs  extends BaseBiz<SysRoleMapper, SysRole> {
    @Autowired
    SysRoleMemberMapper roleMemberMapper;

    @Autowired
    SysResourceAuthorityMapper resourceAuthorityMapper;

    @Autowired
    SysMenuMapper sysMenuMapper;

    @Autowired
    SysUserMapper userMapper;

    @Override
    public void insertSelective(SysRole entity) {
        if (CoreConstants.ROOT.equals(entity.getParentId())) {
            entity.setPath("/" + entity.getCode());
        } else {
            SysRole parent = this.selectById(entity.getParentId());
            entity.setPath(parent.getPath() + "/" + entity.getCode());
        }
        super.insertSelective(entity);
    }

    @Override
    public void updateById(SysRole entity) {
        if (CoreConstants.ROOT.equals(entity.getParentId())) {
            entity.setPath("/" + entity.getCode());
        } else {
            SysRole parent = this.selectById(entity.getParentId());
            entity.setPath(parent.getPath() + "/" + entity.getCode());
        }
        super.updateById(entity);
    }

    /**
     * 获取群组关联用户
     *
     * @param groupId
     * @return
     */
    public GroupUsers getGroupUsers(int groupId) {
        return new GroupUsers(userMapper.selectMemberByGroupId(groupId), userMapper.selectLeaderByGroupId(groupId));
    }

    /**
     * 变更群主所分配用户
     *
     * @param groupId
     * @param members
     * @param leaders
     */
    public void modifyGroupUsers(int groupId, String members, String leaders) {
        SysRoleMember e = new SysRoleMember();
        e.setGroupId(groupId);
        roleMemberMapper.delete(e);
        if (members!=null && !members.isEmpty()) {
            String[] mem = members.split(",");
            for (String m : mem) {
                SysRoleMember tm = new SysRoleMember();
                tm.setGroupId(groupId);
                tm.setUserId(Integer.valueOf(m));
                roleMemberMapper.insertSelective(tm);
            }
        }
        if (leaders!=null && !leaders.isEmpty()) {
            String[] mem = leaders.split(",");
            for (String m : mem) {
                SysRoleMember tm = new SysRoleMember();
                tm.setGroupId(groupId);
                tm.setUserId(Integer.valueOf(m));
                tm.setLeader(1);
                roleMemberMapper.insertSelective(tm);
            }
        }
    }

    public void InsertGroupUsers(int groupId, Integer uid) {
        SysRoleMember tm = new SysRoleMember();
        tm.setGroupId(groupId);
        tm.setUserId(uid);
        roleMemberMapper.insertSelective(tm);
    }

    public void InsertGroupLeaderUsers(int groupId, Integer uid) {
        SysRoleMember tm = new SysRoleMember();
        tm.setGroupId(groupId);
        tm.setUserId(uid);
        tm.setLeader(1);
        roleMemberMapper.insertSelective(tm);
    }

    /**
     * 变更群组关联的菜单
     *
     * @param groupId
     * @param menus
     */
    public void modifyAuthorityMenu(int groupId, Integer[] menus) {
        resourceAuthorityMapper.deleteByAuthorityIdAndResourceType(groupId, CoreConstants.RESOURCE_TYPE_MENU);
        List<SysMenu> menuList = sysMenuMapper.selectAll();
        Map<Integer, Integer> map = new HashMap<>();
        for (SysMenu menu : menuList) {
            map.put(menu.getId(), menu.getParentId());
        }
        Set<Integer> relationMenus = new HashSet<>();
        relationMenus.addAll(Arrays.asList(menus));
        SysResourceAuthority authority = null;
        for (Integer menuId : menus) {
            findParentID(map, relationMenus, menuId);
        }
        for (Integer menuId : relationMenus) {
            authority = new SysResourceAuthority();
            authority.setAuthorityType(CoreConstants.AUTHORITY_TYPE_GROUP);
            authority.setResourceType(CoreConstants.RESOURCE_TYPE_MENU);
            authority.setAuthorityId(groupId);
            authority.setResourceId(menuId);
            authority.setParentId(-1);
            resourceAuthorityMapper.insertSelective(authority);
        }
    }

    private void findParentID(Map<Integer, Integer> map, Set<Integer> relationMenus, Integer id) {
        Integer parentId = map.get(id);
        if (CoreConstants.ROOT.equals(id)) {
            return;
        }
        relationMenus.add(parentId);
        findParentID(map, relationMenus, parentId);
    }

    /**
     * 分配资源权限
     *
     * @param groupId
     * @param menuId
     * @param elementId
     */
    public void modifyAuthorityElement(int groupId, int menuId, int elementId) {
        SysResourceAuthority authority = new SysResourceAuthority();
        authority.setAuthorityType(CoreConstants.AUTHORITY_TYPE_GROUP);
        authority.setResourceType(CoreConstants.RESOURCE_TYPE_BTN);
        authority.setAuthorityId(groupId);
        authority.setResourceId(elementId);
        authority.setParentId(-1);
        resourceAuthorityMapper.insertSelective(authority);
    }

    /**
     * 移除资源权限
     *
     * @param groupId
     * @param menuId
     * @param elementId
     */
    public void removeAuthorityElement(int groupId, int menuId, int elementId) {
        SysResourceAuthority authority = new SysResourceAuthority();
        authority.setAuthorityId(groupId);
        authority.setResourceId(elementId);
        authority.setParentId(-1);
        resourceAuthorityMapper.delete(authority);
    }

    /**
     * 获取群组关联的菜单
     *
     * @param groupId
     * @return
     */
    public List<AuthorityMenuTree> getAuthorityMenu(int groupId) {
        List<SysMenu> menus = sysMenuMapper.selectMenuByAuthorityId(groupId, CoreConstants.AUTHORITY_TYPE_GROUP);
        List<AuthorityMenuTree> trees = new ArrayList<AuthorityMenuTree>();
        AuthorityMenuTree node = null;
        for (SysMenu menu : menus) {
            node = new AuthorityMenuTree();
            node.setText(menu.getTitle());
            BeanUtils.copyProperties(menu, node);
            trees.add(node);
        }
        return trees;
    }

    /**
     * 获取群组关联的资源
     *
     * @param groupId
     * @return
     */
    public List<Integer> getAuthorityElement(int groupId) {
        SysResourceAuthority authority = new SysResourceAuthority();
        authority.setAuthorityType(CoreConstants.AUTHORITY_TYPE_GROUP);
        authority.setResourceType(CoreConstants.RESOURCE_TYPE_BTN);
        authority.setAuthorityId(groupId);
        List<SysResourceAuthority> authorities = resourceAuthorityMapper.select(authority);
        List<Integer> ids = new ArrayList<Integer>();
        for (SysResourceAuthority auth : authorities) {
            ids.add(auth.getResourceId());
        }
        return ids;
    }
}
